﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Palsta.Core
{
    public class EventObserver
    {
        protected String _jsEventName = "";
        protected String _listenNodeName = "";
        protected String _jsCallback = "";
        protected static IList<EventObserver> _observers = new List<EventObserver>();
        public EventObserver(String EventName, String NodeName, String Callback)
        {
            _jsEventName = EventName;
            _listenNodeName = NodeName;
            _jsCallback = Callback;
        }

        public String EventName
        {
            get
            {
                return _jsEventName;
            }
        }

        public String ListenNodeName
        {
            get
            {
                return _listenNodeName;
            }
        }

        public String Callback
        {
            get
            {
                return _jsCallback;
            }
        }

        public override bool Equals(object obj)
        {
            EventObserver target = obj as EventObserver;
            if (target == null) return false;
            if (target == this) return true;
            if (target._jsCallback == this._jsCallback && target._jsEventName == this._jsEventName && target._listenNodeName == this._listenNodeName)
            {
                return true;
            }
            return false;
        }

        public virtual String ToJSonNode()
        {
            return "{ event : '" + EventName + "', element_id : '" + ListenNodeName + "', callback : " + Callback + "}";
        }

        public override int GetHashCode()
        {
            return _jsCallback.GetHashCode() + _jsEventName.GetHashCode() + _listenNodeName.GetHashCode();
        }

        public static void AddObserver(EventObserver observer){
            if (!_observers.Contains(observer))
            {
                _observers.Add(observer);
            }
        }

        public static void RemoveObserver(EventObserver observer)
        {
            if (_observers.Contains(observer))
            {
                _observers.Remove(observer);
            }
        }

        public static String ToJSon()
        {
            String json = "";
            foreach (EventObserver o in _observers)
            {
                if (json.Length == 0)
                {
                    json = o.ToJSonNode();
                }
                else
                {
                    json += ",\r\n" + o.ToJSonNode();
                }
            }
            json = "var EventMaps = [\r\n" + json + "\r\n];";
            return json;
        }
    }
}
